package com.lening.common.service.impl;


import com.lening.common.service.RedisService;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author 牛强
 * @datetime 2024/4/23 9:54
 * @description 类对象
 */
@Service
@ConditionalOnClass(RedisTemplate.class)
public class RedisServiceImpl implements RedisService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean save(String key, String value) {
        if (!StringUtils.hasText(key)) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, value);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }

    @Override
    public boolean save(String key, String value, long timeout, TimeUnit unit) {
        if (!StringUtils.hasText(key) || unit == null) {
            return false;
        }
        try {
            redisTemplate.opsForValue().set(key, value, timeout, unit);
            return true;
        } catch (RuntimeException e) {
            return false;
        }
    }

    @Override
    public String get(String key) {
        if (!StringUtils.hasText(key)) {
            return null;
        }
        try {
            return redisTemplate.opsForValue().get(key);
        } catch (RuntimeException e) {
            return null;
        }
    }

    @Override
    public boolean hasKey(String key) {
        if (!StringUtils.hasText(key)) {
            return false;
        }
        try {
            return Boolean.TRUE.equals(redisTemplate.hasKey(key));
        } catch (RuntimeException e) {
            return false;
        }
    }

    @Override
    public boolean delKey(String key) {
        if (!StringUtils.hasText(key)) {
            return false;
        }
        try {
            return Boolean.TRUE.equals(redisTemplate.delete(key));
        } catch (RuntimeException e) {
            return false;
        }
    }

    @Override
    public boolean expire(String key, long timeout, TimeUnit unit) {
        if (!StringUtils.hasText(key) || unit == null) {
            return false;
        }
        try {
            return Boolean.TRUE.equals(redisTemplate.expire(key, timeout, unit));
        } catch (RuntimeException e) {
            return false;
        }
    }
}
